package com.zs;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Description:
 *
 * @author: zsq-1186
 * Date: 2017-08-18-12:17
 */
public class ReceiveTopic {
    private static final String EXCHANGE_NAME = "ex_logs_topic";
    private static final String[] routing_keys  = { "kernal.info", "cron.warning", "auth.info", "kernel.critical" };

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");


        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();

        String queue=channel.queueDeclare().getQueue();
        channel.exchangeDeclare(EXCHANGE_NAME,"topic");
        //相比于 direct 可以通过 routingKey来匹配感兴趣的内容
        channel.queueBind(queue,EXCHANGE_NAME,"kernal.*");
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        Consumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(queue,true,consumer);
    }
}
